<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use DB;
use App\Extensions\WeixinPay\jsapi;

class PaymentController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->middleware('CheckUserLogin')->except(['weixinpay_notify']);
    }

    public function goldPay(Request $request)
    {
        DB::beginTransaction();
        try {
            $gold = $request->gold;
            $gold_pay_data = getColumnArray('gold', $gold, Config('common.gold_pay_data'));
            if (empty($gold_pay_data)) return jsonFailed('未知的金币值');
            $price = $gold_pay_data['price'];
            $user = $request->get('user');

            // 支付记录数据
            $data_payment_log = [];
            $data_payment_log['number'] = 'i' . time();
            $data_payment_log['user_id'] = $user->id;
            $data_payment_log['price'] = $price;
            $data_payment_log['gold'] = $gold;
            $data_payment_log['subject'] = '购买金币';
            $data_payment_log['body'] = '购买金币';
            DB::table('payment_log')->insert($data_payment_log);
            DB::commit();

            // 微信支付
            $mchid = Config('common.wxmc.mchid');
            $appid = Config('common.wxmp.AppID');
            $appKey = Config('common.wxmp.AppSecret');
            $apiKey = Config('common.wxmc.apiKey');

            $wxPay = new \App\Extensions\WeixinPay\jsapi($mchid, $appid, $appKey, $apiKey);
            $openId = $user->wx_openid;

            $outTradeNo = $data_payment_log['number'];
            $payAmount = $data_payment_log['price'];
            $orderName = $data_payment_log['subject'];
            $notifyUrl = Config('app.url') . '/api/payment/weixinpay_notify';
            $payTime = time();
            $jsApiParameters = $wxPay->createJsBizPackage($openId, $payAmount, $outTradeNo, $orderName, $notifyUrl, $payTime);

            return jsonSuccess($jsApiParameters);
        } catch (\Throwable $th) {
            DB::rollBack();
            return jsonFailed($th->getMessage());
        }
    }

    public function weixinpay_notify(Request $request)
    {
        $log = '';
        try {
            $mchid = Config('common.wxmc.mchid'); // 微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
            $appid = Config('common.wxmp.AppID'); // 微信支付申请对应的公众号的APPID
            $appKey = Config('common.wxmp.AppSecret'); // 微信支付申请对应的公众号的APP Key
            $apiKey = Config('common.wxmc.apiKey'); //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
            $wxPay = new \App\Extensions\WeixinPay\notify($mchid, $appid, $apiKey);
            $res = $wxPay->notify();

            $out_trade_no = $res['out_trade_no'];
            $payment_log = DB::table('payment_log')->where('number', $out_trade_no)->first();
            if (empty($payment_log)) exit('ERROR');

            DB::beginTransaction();
            DB::table('payment_log')->where('number', $out_trade_no)->update(['status' => 1, 'trade_no' => $res['transaction_id']]);
            DB::table('user')->where('id', $payment_log->user_id)->increment('gold', $payment_log->gold);
            DB::table('gold_log')->insert(['user_id' => $payment_log->user_id, 'gold' => $payment_log->gold]);
            DB::commit();
            exit('SUCCESS');
        } catch (\Throwable $th) {
            DB::rollBack();
            $log .= "ERROR\n";
            $log .= $th->getMessage();
            logWrite(json_encode($res), 'weixinpay');
            exit('ERROR');
        }
    }
}
